# _*_ coding:utf-8 _*_
# @Time  : 2023.08.01
# @Author: zizlee

from fastapi import APIRouter, Depends, Query
from utils.jwt_token import TokenPayload
from db_utils import DepartmentDataBaseConnection, BaseDatabaseConnection
from response import APIResponse
from constant.variety import VarietyConstants
from constant.user import UserType
from constant.section_scope import SectionScope
from settings import FILE_STORAGE_HOST


class Investment:

    def get_user_access_variety(self, user_id: int, sec_key: str):
        with BaseDatabaseConnection() as conn:
            conn.cursor.execute("""
                SELECT id,variety_en FROM ruizhi_user_section_variety 
                WHERE user_id=%s AND sec_key=%s AND expire_date>=CURDATE();
            """, [user_id, sec_key])
            v_list = list(conn.cursor.fetchall())
        return [v['variety_en'] for v in v_list]

    def format_strategy(self, strategy_list):
        format_data = []
        for item in strategy_list:
            detail = eval(item['strategy'])

            # 转换数据类型
            p_num = 4
            sp, tp, cp = item['strategy_price'], item['target_price'], item['cutloss_price']
            sp = int(sp) if int(sp) == round(sp, p_num) else round(sp, p_num)
            tp = int(tp) if int(tp) == round(tp, p_num) else round(tp, p_num)
            cp = int(cp) if int(cp) == round(cp, p_num) else round(cp, p_num)

            # 根据type显示策略文字内容
            if item['type'] == 1:  # 单边策略
                detail = detail[0]
                v_name = ''
                if VarietyConstants.is_in(item['variety_en']):
                    v_name = VarietyConstants.get_variety_name(item['variety_en'])
                direction = '做多' if detail['direction'] == 'B' else '做空'
                strategy = f'【交易策略】建议于{sp}{detail["price_unit"]}附近{direction}{v_name}{detail["contract"]}，' \
                           f'目标{tp}{detail["price_unit"]}，止损{cp}{detail["price_unit"]}。' \
                           f'{item["description"]}'
                hands_text = detail['hands']
            elif item['type'] == 2:  # 双品种套利策略
                v1_data, v2_data = detail
                d1 = '做多' if v1_data["direction"] == 'B' else '做空'
                d2 = '做多' if v2_data['direction'] == 'B' else '做空'
                v1_name = v2_name = ''
                if VarietyConstants.is_in(v1_data['variety_en']):
                    v1_name = VarietyConstants.get_variety_name(v1_data['variety_en'])
                    v2_name = VarietyConstants.get_variety_name(v2_data['variety_en'])

                # 组织数据
                strategy = f'【套利策略】{v1_name}{v1_data["contract"]}与{v2_name}{v2_data["contract"]}合约价差为{sp}时，' \
                           f'建议{d1}{v1_name}{v1_data["contract"]},{d2}{v2_name}{v2_data["contract"]}，' \
                           f'价差为{tp}附近止盈，止损价差为{cp}附近。{item["description"]}'

                hands_text = v1_data['hands']
            elif item['type'] == 3:  # 多品种套利策略
                strategy = '【套利策略】建议同时'
                for stv_item in detail:  # stv= strategy_variety
                    d = '做多' if stv_item['direction'] == 'B' else '做空'
                    v_name = VarietyConstants.get_variety_name(stv_item['variety_en'])
                    strategy += f'{d}{v_name}{stv_item["contract"]},数量:{stv_item["hands"]}手;'
                strategy = strategy[:-1] + '。'
                strategy += item['description']
                hands_text = ''
            else:
                continue
            # open_time = item['open_time'] if item['open_time'] else ''
            close_time = item['close_time'] if item['close_time'] else ''
            format_data.append({
                'id': item['id'],
                'content': strategy,
                'strate_time': item['create_time'],
                'inactive': True if close_time else False
            })
        return format_data

    def short_investment(self, payload: TokenPayload, page: int, page_size: int):  # 分页获取投资策略
        utp = payload.user_type()
        if utp == UserType.REGISTER_USER:
            return APIResponse.success(data={'data': [], 'page': 1, 'page_size': page_size, 'total_count': 0})

        if utp not in UserType.VARIETY_AUTH_SETS:
            sql = """
                SELECT id,create_time,open_time,type,variety_en,description,close_time,strategy_price,target_price,cutloss_price,
                strategy FROM info_strategy WHERE is_delete=0 AND is_ruizhi=1
                ORDER BY create_time DESC;
            """
            prm = []

        else:
            # 查询用户有短线策略权限的品种
            v_list = self.get_user_access_variety(user_id=payload.user_id(), sec_key=SectionScope.SHORT_STRATEGY_KEY)
            if len(v_list) < 1:
                return APIResponse.success(data={'data': [], 'page': 1, 'page_size': page_size, 'total_count': 0})
            sql = """
                SELECT id,create_time,open_time,type,variety_en,description,close_time,strategy_price,target_price,cutloss_price,
                strategy FROM info_strategy WHERE is_delete=0 AND is_ruizhi=1 AND variety_en in %s
                ORDER BY create_time DESC;
            """
            prm = [v_list]
        with DepartmentDataBaseConnection() as conn:
            ret = conn.query_paginator(sql, param=prm, page=page, page_size=page_size)
        data_list = self.format_strategy(ret['rows'])
        return APIResponse.success(data={'data': data_list,
                                         'page': ret['page'], 'page_size': ret['page_size'],
                                         'total_count': ret['total_count']})

    def long_investment(self, payload: TokenPayload, page: int, page_size: int):  # 分页获取投资方案
        utp = payload.user_type()
        if utp == UserType.REGISTER_USER:
            return APIResponse.success(data={'data': [], 'page': 1, 'page_size': page_size, 'total_count': 0})
        if utp not in UserType.VARIETY_AUTH_SETS:
            sql = """
                SELECT id,create_time,active_date,expire_date,title,filepath
                FROM exchange_plan WHERE is_delete=0 AND is_ruizhi=1
                ORDER BY create_time DESC;
            """
            prm = []
        else:
            # 用户有中长线策略权限的品种
            v_list = self.get_user_access_variety(user_id=payload.user_id(), sec_key=SectionScope.LONG_STRATEGY_KEY)
            if len(v_list) < 1:
                return APIResponse.success(data={'data': [], 'page': 1, 'page_size': page_size, 'total_count': 0})
            v_list_string = '-' + ',-'.join(v_list) + ','

            # SELECT id,title,varieties,CONCAT('-', REPLACE ( varieties, ',', ',|-' ), ',') FROM exchange_plan
            # WHERE '-C,' REGEXP CONCAT('-', REPLACE ( varieties, ',', ',|-' ), ',');

            sql = """
                SELECT id,create_time,active_date,expire_date,title,filepath FROM exchange_plan
                WHERE is_delete=0 AND is_ruizhi=1 AND %s REGEXP CONCAT('-',REPLACE(varieties, ',', ',|-' ), ',');
            """
            prm = [v_list_string]
        with DepartmentDataBaseConnection() as conn:
            ret = conn.query_paginator(sql, prm, page=page, page_size=page_size)
        data_list = []
        for row in ret['rows']:
            data_list.append({
                'id': row['id'],
                'create_date': row['create_time'][0:11],
                'active_date': row['active_date'],
                'expire_date': row['expire_date'],
                'title': row['title'],
                'pdf_url': FILE_STORAGE_HOST + row['filepath']
            })
        return APIResponse.success(data={'data': data_list,
                                         'page': ret['page'], 'page_size': ret['page_size'],
                                         'total_count': ret['total_count']})


investment_api = APIRouter()


@investment_api.get('/short/')  # 短线策略
def short_investment_strategy(payload: TokenPayload = Depends(TokenPayload),
                              page: int = Query(1), page_size: int = Query(10)):
    return Investment().short_investment(payload=payload, page=page, page_size=page_size)


@investment_api.get('/long/')  # 中长期策略
def long_investment_strategy(payload: TokenPayload = Depends(TokenPayload),
                             page: int = Query(1), page_size: int = Query(10)):
    return Investment().long_investment(payload=payload, page=page, page_size=page_size)
